import sys
from PyQt6.QtWidgets import QApplication,QMainWindow,QWidget,QSplitter,QVBoxLayout
from PyQt6.QtWidgets import QPushButton,QFileDialog
from PyQt6.QtWidgets import QSizePolicy,QMessageBox,QMenuBar,QMenu
from PyQt6.QtCore import Qt,QTimer,QMetaObject,QSize,QCoreApplication,QRect
from PyQt6.QtGui import QIcon, QGuiApplication,QAction
from datetime import datetime,timedelta
from dateutil.relativedelta import relativedelta
from utils.Logger import LogPrint
from views.LeftNavigationView import LeftNavigationView,LeftNavigationItem
from views.DbmsMgrView import DbmsMgrView
from views.DbmsOperateView import DbmsOperateView

 
class Ui_MainWindow(QMainWindow):
    """主窗体类"""
    def __init__(self):


        """构造函数"""
        super(Ui_MainWindow,self).__init__()        # 调用父类初始化函数，需要调用父类初始化才能正常使用父类定一的变量


        ##初始化变量
        self.current_view=None
        self.current_month_view=None
        self.current_year_view=None
        self.last_month_view=None
        # 获取当前屏幕对象
        screen = QGuiApplication.screens()[0]
        
        # 获取屏幕的几何形状（包括任务栏等界面元素）
        screen_geometry = screen.geometry()
        
        # 获取屏幕的宽度
        screen_width = screen_geometry.width()

        self.overallWindowWidth=screen_width
        LogPrint.debug('screen_width',screen_width)
        self.overallWindowHeight=600

        # 其他代码块
        #self.setWindowFlag(Qt.WindowType.MSWindowsFixedSizeDialogHint)
        self.setupUi(self)

        #监听窗体大小变化
        #self.resizeEvent=self.on_change_window

        

    def setupUi(self, MainWindow):
        MainWindow.setWindowTitle("文件管理器")
        MainWindow.resize(self.overallWindowWidth, self.overallWindowHeight)

        self.setupMenuBar()

        self.setupCentralWidget()
        self.setupStatusBar()
        LogPrint.info('Ui_MainWindow init finish')
        #用于自动连接信号和槽的方法。它会查找对象的所有属性，
        # 如果属性名称符合特定的命名规则（即以 "on_" 开头），
        # 那么会尝试将该属性自动与相应的信号连接起来。
        QMetaObject.connectSlotsByName(MainWindow)

    #菜单栏
    def setupMenuBar(self):
        pass

        # self.menubar = QMenuBar(parent=self)
        # self.menubar.setGeometry(QRect(0, 0, self.overallWindowWidth, 22))
        # self.menubar.setObjectName("menubar")

        # #设置账单关系
        # self.setup_menu_bill_setting()
        # self.setup_menu_bill_import()
        # #帮助菜单
        # self.set_menu_help()
        

    #账单设置菜单
    def setup_menu_bill_setting(self):

        _translate = QCoreApplication.translate

        self.menu_bill_relation = QMenu(parent=self.menubar)
        self.menu_bill_relation.setObjectName("menu")
        self.menubar.addMenu(self.menu_bill_relation)
        self.menu_bill_relation.setTitle(_translate("MainWindow", "账单设置"))
        self.menu_bill_relation.triggered.connect(self.onMenuClicked)

        #增加子菜单
        self.action_bill_set_common_rel = QAction(parent=self)
        icon1 = QIcon()
        icon1.addPixmap(ImageUtils.getQPixmap("icon_intro.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action_bill_set_common_rel.setIcon(icon1)
        self.action_bill_set_common_rel.setObjectName("menu_bill_set_common_rel")
        self.action_bill_set_common_rel.setText('设置通用对应关系')
        self.menu_bill_relation.addAction(self.action_bill_set_common_rel)

        #增加子菜单
        self.action_bill_set_rel = QAction(parent=self)
        icon1 = QIcon()
        icon1.addPixmap(ImageUtils.getQPixmap("icon_intro.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action_bill_set_rel.setIcon(icon1)
        self.action_bill_set_rel.setObjectName("menu_bill_set_rel")
        self.action_bill_set_rel.setText('设置对应关系')
        self.menu_bill_relation.addAction(self.action_bill_set_rel)

        #增加子菜单---分类
        self.action_bill_set_classify = QAction(parent=self)
        icon1 = QIcon()
        icon1.addPixmap(ImageUtils.getQPixmap("icon_intro.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action_bill_set_classify.setIcon(icon1)
        self.action_bill_set_classify.setObjectName("menu_bill_set_classify")
        self.action_bill_set_classify.setText('分类管理')
        self.menu_bill_relation.addAction(self.action_bill_set_classify)

    #账单导入菜单
    def setup_menu_bill_import(self):

        _translate = QCoreApplication.translate

        #导入账单
        self.menu_import = QMenu(parent=self.menubar)
        self.menu_import.setObjectName("menu")
        self.menubar.addMenu(self.menu_import)
        self.menu_import.setTitle(_translate("MainWindow", "导入账单"))

        

        #增加子菜单
        self.action_import_wechat = QAction(parent=self)
        icon1 = QIcon()
        icon1.addPixmap(ImageUtils.getQPixmap("icon_intro.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action_import_wechat.setIcon(icon1)
        self.action_import_wechat.setObjectName("menu_wechat")
        self.action_import_wechat.setText('微信账单')
        self.action_import_alipay = QAction()
        icon2 = QIcon()
        icon2.addPixmap(ImageUtils.getQPixmap("icon_about.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action_import_alipay.setIcon(icon2)
        self.action_import_alipay.setObjectName("menu_alipay")
        self.action_import_alipay.setText('支付宝账单')

        self.action_manual_entry = QAction()
        icon2 = QIcon()
        icon2.addPixmap(ImageUtils.getQPixmap("icon_about.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action_manual_entry.setIcon(icon2)
        self.action_manual_entry.setObjectName("menu_manual")
        self.action_manual_entry.setText('人工录入')

        self.menu_import.addAction(self.action_import_wechat)
        self.menu_import.addAction(self.action_import_alipay)
        self.menu_import.addAction(self.action_manual_entry)

        #菜单绑定点击事件
        self.menu_import.triggered.connect(self.onMenuClicked)
        

    def set_menu_help(self):

        _translate = QCoreApplication.translate

        self.menu = QMenu(parent=self.menubar)
        self.menu.setObjectName("menu")
        self.menubar.addMenu(self.menu)

        self.setMenuBar(self.menubar)
        self.menu.setTitle(_translate("MainWindow", "帮助"))

        #增加子菜单
        self.action = QAction(parent=self)
        icon1 = QIcon()
        icon1.addPixmap(ImageUtils.getQPixmap("icon_intro.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action.setIcon(icon1)
        self.action.setObjectName("menu_intro")
        self.action.setText('功能介绍')
        self.action_2 = QAction()
        icon2 = QIcon()
        icon2.addPixmap(ImageUtils.getQPixmap("icon_about.svg"), QIcon.Mode.Normal, QIcon.State.Off)
        self.action_2.setIcon(icon2)
        self.action_2.setObjectName("menu_about")
        self.action_2.setText('关于')

        self.menu.addAction(self.action)
        self.menu.addAction(self.action_2)

        
        self.menu.triggered.connect(self.onMenuClicked)

    ###菜单点击事件
    def onMenuClicked(self,m):
        pass
        # if m.objectName()=="menu_intro":
        #     QMessageBox.information(None,'功能介绍','1、支持pdf按每页转图片功能\n2、支持整个pdf按每页合成一张图片\n3、支持多个pdf按合成一张长图片')
        # elif m.objectName()=="menu_about":
        #     QMessageBox.information(None,'关于','版本号:1.0')
        # elif m.objectName()=="menu_wechat":
        #     self.wechat_dialog = ImportBillDialog.Ui_Dialog()
        #     self.wechat_dialog.show()
        # elif m.objectName()=="menu_alipay":
        #     self.wechat_dialog = ImportBillDialog.Ui_Dialog(type='alipay')
        #     self.wechat_dialog.show()
        # elif m.objectName()=="menu_bill_set_rel":
        #     self.bill_relation_dialog = BillRelationDialog.Ui_Dialog()
        #     self.bill_relation_dialog.show()
        # elif m.objectName()=="menu_bill_set_common_rel":
        #     self.bill_relation_dialog = CommonBillRelationDialog.Ui_Dialog()
        #     self.bill_relation_dialog.show()
        # elif m.objectName()=="menu_bill_set_classify":
        #     self.classify_mgr_dialog = ClassifyMgrDialog.Ui_Dialog()
        #     self.classify_mgr_dialog.show()
        # elif m.objectName()=="menu_manual":
        #     self.manual_dialog = ManualRetryDialog.Ui_Dialog()
        #     self.manual_dialog.show()
        
    ####
    ####主界面显示区域
    ####
    def setupCentralWidget(self):

        self.splitter = QSplitter(Qt.Orientation.Horizontal)
        self.splitter.setChildrenCollapsible(False) 
        self.left_navi_view=LeftNavigationView(callback=self.on_navigation_item_clicked)
        self.splitter.addWidget(self.left_navi_view)
        self.current_view=DbmsMgrView()
        self.splitter.addWidget(self.current_view)
        
        self.splitter.setStretchFactor(0,3)
        self.splitter.setStretchFactor(1,7)

        self.setCentralWidget(self.splitter)

    #左侧导航栏点击回调
    def on_navigation_item_clicked(self,item):
        LogPrint.debug(item)
        if item==LeftNavigationItem.item_dbms_operate:
            #if self.current_month_view is None:
            self.current_view=DbmsOperateView()
            self.splitter.replaceWidget(1,self.current_view)
        elif item==LeftNavigationItem.item_dbms_db_instance:
            #if self.current_month_view is None:
            self.current_view=DbmsMgrView()
            self.splitter.replaceWidget(1,self.current_view)

        self.splitter.setStretchFactor(0,3)
        self.splitter.setStretchFactor(1,7)
    

    #窗口变化
    def on_change_window(self, event):
        LogPrint.debug(f'Window resized to: {self.size()}')
        self.current_view.on_change_window_size(self.size())
        # 调用父类的resizeEvent以便继续处理事件
        super().resizeEvent(event)
    
    #状态栏显示当前时间
    def setupStatusBar(self):
        self.statusbar = self.statusBar()
        self.statusbar.showMessage("时间准备就绪")
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_time)
        self.timer.start(1000)  # 每秒更新一次

    def update_time(self):
        # 当前日期时间
        now = datetime.now()
        
        # 格式化日期时间
        formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
        time_string = "当前时间: {}".format(formatted_date)
        self.statusbar.showMessage(time_string, 0)

    def onShowMessage(self,errMsg):
        QMessageBox.warning(None,'系统错误',errMsg)

    

def main():
    ##如果使用pyinstall打包，打开下面这段代码

    # try:           
    #     pyi_splash.close()
    # except ImportError:
    #     pass
    ###
    app = QApplication(sys.argv)
    main = Ui_MainWindow()
    main.setMinimumWidth(800)
    main.show()
    sys.exit(app.exec())


if __name__ == "__main__":
    main()